import sys

def get_input():
    shell_name, method, p, q, e, text = sys.argv
    return int(p), int(q), int(e), method, int(text)

def mygcd(a,b):
    if a < b:
        a,b = b,a
    if b != 0:
        return mygcd(b, a%b)
    return a

def extended_Euclid(remainder,shang,chushu):
    if remainder != 1 or flag != 1:
        flag = 1
        a,b = extended_Euclid(chushu % remainder, chushu / remainder, remainder)
        print a,b
        return a * (-1 * shang) + b ,a
    else:
        return -1*shang,1

def extended_Euclid2(fi_n,e,not_used):
    for i in xrange(1000):
        if (i * fi_n + 1) % e == 0:
            return (i * fi_n + 1) / e

def get_res(p,q,e):
    n = p*q
    fi_n = (p-1) * (q-1)
    return extended_Euclid2(fi_n,e,0)

def encode(e,n,num):
    res = num
    while e != 1:
        res *= num
        e -= 1
        if res > n:
            res %= n
    return res

#def decode(d,n,num):
    #res = num
    #while d != 1:
        #res *= num
        #d -= 1
        #if res > n:
            #res %= n
    #return res

def code_or(e,d,n,num):
    if sys.argv[1] == "d":
        print "the result of decode is ",
        return encode(d,n,num) % n
    elif sys.argv[1] == "e":
        print "the result of encode is ",
        return encode(e,n,num) % n
    elif sys.argv[1] == "s":
        print "the signature is ",
        return encode(d,n,num) % n
    elif sys.argv[1] == "c":
        print "the result of check is ",
        return encode(e,n,num) % n
    else:
        print "error argument"
        exit()

if __name__ == "__main__":
    p,q,e,method,text = get_input()
    d = get_res(p,q,e)
    print "d = ",d
    print "e = ",e
    print code_or(e,d,p*q,text)

